package com.yiwenup.leetcode.top_interview_150;

import java.util.Stack;

/**
 * 文件描述
 *
 * @Project struct-algorithm
 * @Package com.yiwenup.leetcode.top_interview_150
 * @Author yiwenup
 * @Date 2024-12-23 20:46:22
 * @Description https://leetcode.cn/problems/evaluate-reverse-polish-notation/description/?envType=study-plan-v2&envId=top-interview-150
 */
public class No0150 {

    private int idx;
    public int evalRPN(String[] tokens) {
        idx = tokens.length - 1;
        return recur(tokens);
    }

    private int recur(String[] tokens) {
        String token = tokens[idx--];
        int num1;
        int num2;
        switch (token) {
            case "+":
                num1 = recur(tokens);
                num2 = recur(tokens);
                return num1 + num2;
            case "*":
                num1 = recur(tokens);
                num2 = recur(tokens);
                return num1 * num2;
            case "-":
                num1 = recur(tokens);
                num2 = recur(tokens);
                return num2 - num1;
            case "/":
                num1 = recur(tokens);
                num2 = recur(tokens);
                return num2 / num1;
            default:
                return Integer.parseInt(token);
        }
    }

    public int evalRPN2(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        for (String token : tokens) {
            if (!"+".equals(token) && !"-".equals(token) && !"*".equals(token) && !"/".equals(token)) {
                stack.push(Integer.valueOf(token));
                continue;
            }
            Integer num1 = stack.pop();
            Integer num2 = stack.pop();
            int res = 0;
            switch (token) {
                case "+":
                    res = num1 + num2;
                    break;
                case "*":
                    res = num1 * num2;
                    break;
                case "-":
                    res = num2 - num1;
                    break;
                case "/":
                    res = num2 / num1;
                    break;
                default:
                    break;
            }
            stack.push(res);
        }
        return stack.pop();
    }
}
